import React from 'react';
import { inject, observer } from 'mobx-react';
import {WeaTableNew} from 'comsMobx';
const WeaTable = WeaTableNew.WeaTable;
import * as mobx from 'mobx';
import {WeaErrorPage, WeaHelpfulTip, WeaTools} from 'ecCom';
import {superviseStore} from '../../stores';
import allStore from '../../stores';
import {Button,Modal,message} from 'antd';
import {WeaTop, WeaRightMenu, WeaTab, WeaLeftRightLayout, WeaLeftTree, WeaPopoverHrm, WeaLocaleProvider,WeaDropdown} from 'ecCom';
const getLabel = WeaLocaleProvider.getLabel;
//自定义组件
import {Synergy} from 'weaPortal';
import Condition from './Condition';
import BatchSubmit from '../../asyncComps/BatchSubmit';//批量督办
import SendSms from '../../asyncComps/SendSms';//新建短信
import SendEmail from '../../asyncComps/SendEmail';//新建邮件
import TagTypeSelectDialog from "../../asyncComps/TagTypeSelectDialog"
import {verifySupervise} from '../../util/superviseUtil';
import {toJS} from "mobx";
const { ButtonSelect } = WeaDropdown;
 @inject('superviseStore')

 @observer
class Supervise extends React.Component{

  constructor(props){
    super(props);
    this.doInit(this.props);
  }
  doInit(props){
    const { location,superviseStore } = props;
    superviseStore.init(location.query || {});
    _ListenerCtrl.bind();
  }
  componentDidMount() {
    const { jumpTab } = this.props.superviseStore;
    const { location } = this.props;
    jumpTab(location.query) //督办页通过URl传参的方式指定切换到某个Tab
    // const { hover } = this.props.superviseStore;
    this.timerID=setTimeout(()=>{ 
      $(".wf_attention_div_btn").on("mouseover mouseout",function(event){
          const str = $(this).attr('id').substr($(this).attr('id').indexOf('_'))
          if(event.type == "mouseover"){  
           jQuery("#attentionSpan"+str).css("display","block")
          }else if(event.type == "mouseout"){
           jQuery("#attentionSpan"+str).css("display","none")
          }
         })
   },1000)
  }
  componentDidUpdate(){
    // const { hover } = this.props.superviseStore;
    this.timerID=setTimeout(()=>{ 
      $(".wf_attention_div_btn").on("mouseover mouseout",function(event){
          const str = $(this).attr('id').substr($(this).attr('id').indexOf('_'))
          if(event.type == "mouseover"){  
           jQuery("#attentionSpan"+str).css("display","block")
          }else if(event.type == "mouseout"){
           jQuery("#attentionSpan"+str).css("display","none")
          }
         })
   },1000)
  }
  componentWillUnmount(){
    const { superviseStore } = this.props;
    superviseStore.clearStatus();
    _ListenerCtrl.bind();
    clearTimeout(this.timerID);
  }
  
  componentWillReceiveProps(nextProps) {
    if(this.props.location.key !== nextProps.location.key) {
        const { superviseStore } = this.props;
        superviseStore.clearStatus();
        this.doInit(nextProps);
    }
  }

  render(){
    const {superviseStore, location = {}} = this.props;
    const {loading,title,showSearchAd,form,tableStore,topTab, tabKey, smsVisible, smsParams,showBatchSubmit, emailVisible,fwquery,onSubmitText} = superviseStore;
    const formParams = form.getFormParams() || {};
    const loadingTable = tableStore.loading;

    return(
        <div style={{height:"100%",width:"100%"}} className='wf-pc4mobx-supervise'>
          <WeaPopoverHrm ecId={`${this && this.props && this.props.ecId || ''}_WeaPopoverHrm@x7eogn`} />
          <WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@kmongf`} datas={this.getRightMenu()} collectParams={{favname:title, favouritetype: '2' ,importantlevel:'1'}}>
              <WeaTop ecId={`${this && this.props && this.props.ecId || ''}_WeaTop@iehz5y`}
                title={title}
                loading={loading || loadingTable}
                icon={<i className='icon-coms-workflow' />}
                iconBgcolor='#0079DE'
                buttons={this.getbtns()}
                buttonSpace={10}
                showDropIcon={true}
                dropMenuDatas={this.getRightMenu()}
              >
                <WeaLeftRightLayout ecId={`${this && this.props && this.props.ecId || ''}_WeaLeftRightLayout@fzxvbm`}
                  leftCom={this.getTree()}
                >
                  <WeaTab ecId={`${this && this.props && this.props.ecId || ''}_WeaTab@zlla4g`}
                    datas={topTab}
                    keyParam={'key'}
                    selectedKey={tabKey}
                    onChange={v=>{this.changeTab(v)}}
                    buttonsAd={this.getTabButtonsAd()}
                    searchType={['base','advanced']}
                    setShowSearchAd={bool=>{superviseStore.setShowSearchAd(bool)}}
                    hideSearchAd={()=> superviseStore.setShowSearchAd(false)}
                    showSearchAd={showSearchAd}
                    searchsBaseValue={formParams.requestname}
                    searchsAd={
                        <Condition ecId={`${this && this.props && this.props.ecId || ''}_Condition@zbw3o8`} queryStore={superviseStore} onEnterSearch={this.onEnterSearch} />
                    }
                    onSearch={v=>{superviseStore.getSessionkey()}}
                    onSearchChange={v=>{superviseStore.appendFormFields({requestname:v})}}
                  />
                  <WeaTable ecId={`${this && this.props && this.props.ecId || ''}_WeaTable@4hhagz`}
                      comsWeaTableStore={tableStore}
                      hasOrder={true}
                      needScroll={true}
                      register_table={superviseStore.reLoad}
                      getColumns={this.getColumns}
                  />
                </WeaLeftRightLayout>
              </WeaTop>
          </WeaRightMenu>
          {
              showBatchSubmit && <BatchSubmit ecId={`${this && this.props && this.props.ecId || ''}_BatchSubmit@neredw`}
                  visible={showBatchSubmit}
                  onSubmit={this.batchHandle.bind(this)}
                  onCancel={()=>{superviseStore.setShowBatchSubmit(false)}}
                  onSubmitText={onSubmitText}
                  iconClassName={'icon-coms-daiban'}
              />
          }
          {
            smsVisible && <SendSms ecId={`${this && this.props && this.props.ecId || ''}_SendSms@ksvr9o`} params={mobx.toJS(smsParams)} visible={smsVisible} closeFun={()=>{superviseStore.setSmsVisible(false)}}/>
          }
          {
            emailVisible && <SendEmail ecId={`${this && this.props && this.props.ecId || ''}_SendEmail@r9kqdo`}  visible={emailVisible} fwquery={mobx.toJS(fwquery)} closeFun={()=>{superviseStore.setEmailVisible(false)}}/>
          }
          <Synergy ecId={`${this && this.props && this.props.ecId || ''}_Synergy@xkdt2s`} pathname='/workflow/supervise' requestid="-1" />
          <TagTypeSelectDialog ecId={`${this && this.props && this.props.ecId || ''}_TagTypeSelectDialog@qcr0bn`} curStore={allStore.wfFollowTypeSettingStore} reloadway={"1"} refresh={superviseStore.getSessionkey}/>
          {/* <TagTypeSelectDialog curStore={this.props.superviseStore} reloadway={"1"}/> */}
      </div>
    )
  }

  onEnterSearch = () =>{
    const {superviseStore} = this.props;
    superviseStore.getSessionkey();
    superviseStore.setShowSearchAd(false);
  }

  //tab切换
  changeTab(tabKey){
    const { superviseStore } = this.props;
    superviseStore.tabKey = tabKey;
    superviseStore.getSessionkey();
  }

 getColumns = (columns) => {
     const columnsJS = toJS(columns);
     columnsJS.forEach(col => {
         if(col.dataIndex === "unoperators"){
             const title = (
                 <span>
                     <span title={col.title}>
                        { col.title }
                     </span>
                    {<WeaHelpfulTip ecId={`${this && this.props && this.props.ecId || ''}_WeaHelpfulTip@z8w24p@${col.dataIndex}`} style={{ marginLeft: 5 }} title={getLabel(516719,"可在【个性化设置】中设置未操作者的显示类型")} placement="top" />}
                </span>
         )
             col.title = title;
         }
     });
     return columnsJS;
 }


  //搜索框底部按钮
  getTabButtonsAd() {
    const { superviseStore } = this.props;
    return [
        (<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@ie9t79@search`} type="primary" onClick={()=>{superviseStore.getSessionkey();superviseStore.setShowSearchAd(false);}}>{getLabel(197,'搜索')}</Button>),
        (<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@u8rwmo@reset`} type="ghost" onClick={()=>{superviseStore.clearFormFields();}}>{getLabel(2022,'重置')}</Button>),
        (<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@zoxejm@cancel`} type="ghost" onClick={()=>{superviseStore.setShowSearchAd();}}>{getLabel(31129,'取消')}</Button>)
    ];
  }

  //左侧树
  getTree() {
    const { superviseStore} = this.props;
    const { leftTree,leftTreeCountType, leftTreeCount, forceRender,selectedTreeKey} = superviseStore;
    return (
        <WeaLeftTree ecId={`${this && this.props && this.props.ecId || ''}_WeaLeftTree@nkako7`}
            forceRender={forceRender}
            datas={mobx.toJS(leftTree)}
            countsType={leftTreeCountType}
            counts={mobx.toJS(leftTreeCount)}
            selectedKeys={[selectedTreeKey]}
            onFliterAll={()=>{
                superviseStore.setShowSearchAd(false);
                superviseStore.setSelectedTreeKey("");
                superviseStore.clearFormFields();
                superviseStore.getSessionkey();
            }}
            onSelect={(key,counts,types)=>{
                superviseStore.setShowSearchAd(false);
                superviseStore.setSelectedTreeKey(key);
                superviseStore.setByTree(key,counts,types);
            }}
        />
    )
  }


  //批量督办
  batchHandle(remark = ''){
    const { superviseStore } = this.props;
    const {tableStore,getSessionkey, handleParams} = superviseStore;
    const {method = ''} = handleParams;
    let requestids = '';
    if(method === 'only'){
      requestids = handleParams.requestids;
        verifySupervise(requestids,remark,()=>{
            superviseStore.doSupervise({requestids,remark});
            superviseStore.setShowBatchSubmit(false);
        })
    }else{
      const selectedRowKeys = tableStore.selectedRowKeys;
      const selectedLen = tableStore.selectedRowKeys.length;
      if(selectedLen === 0){
        return;
      }
      requestids = selectedRowKeys.toString();
        let params = {requestids,remark};
        superviseStore.doSupervise(params);
        superviseStore.setShowBatchSubmit(false);
    }
  }
//批量关注
batchAttention(){
  const { superviseStore } = this.props;
  const { sharearg ,tableStore} = superviseStore;
  const {selectedRowKeys} = tableStore;
  let idarr = selectedRowKeys.map(v => {
      const arr = v.split("_");
      const requestid = arr[0];
      return requestid;
  });
  let requestIds = idarr.join(",");
  allStore.wfFollowTypeSettingStore.isSingle = false
  allStore.wfFollowTypeSettingStore.followTypeSelectShow = true
  allStore.wfFollowTypeSettingStore.FollowRequestid = requestIds
}

    //顶部右侧操作按钮方法
  getbtns(){
    const { superviseStore } = this.props;
    const { tableStore } = superviseStore;
    const selectedRowKeys = tableStore.selectedRowKeys;
    let btns = [];
    const datas = [
        { key: 'batchSupervisor',show: getLabel(84561,'批量督办'),selected: true},
        { key: 'batchAttention', show: getLabel(503955,'批量关注') },
      ];
  

    btns.push(
        <ButtonSelect ecId={`${this && this.props && this.props.ecId || ''}_ButtonSelect@06nq0f@batch`} 
            datas={datas} 
            btnProps={{disabled:selectedRowKeys.length <= 0}}
            dropdownProps={{trigger:['click']}}
            dropBtnProps={{title:getLabel(384039,"点击切换批量操作")}}
            btnOnClick={key => {
                if(key === 'batchSupervisor'){
                  superviseStore.setShowBatchSubmit(true)
                }else if(key === 'batchAttention'){
                  let idarr = selectedRowKeys.map(v => {
                      const arr = v.split("_");
                      const requestid = arr[0];
                      return requestid;
                  });
                  let requestIds = idarr.join(",");
                  allStore.wfFollowTypeSettingStore.isSingle = false
                  allStore.wfFollowTypeSettingStore.followTypeSelectShow = true
                  allStore.wfFollowTypeSettingStore.FollowRequestid = requestIds
                  // if(idarr.length==1){
                  //     window.followTypeSettingStore.getWorkflowAttentionTypeSet(idarr[0])
                  // }else{
                  //     window.followTypeSettingStore.getWorkflowAttentionTypeSet()
                  // }
                }
            }} 
            menuOnClick={(key, e) => superviseStore.clickButttonDrop(key) }
        />
    );
    return btns;
  }


    //右键菜单方法
   getRightMenu(){
      const { superviseStore ,location} = this.props;
      const { tableStore, form , operBtnKey} = superviseStore;
      const selectedRowKeys = tableStore.selectedRowKeys;
      const selectedLen = tableStore.selectedRowKeys.length;
      const formParams = form.getFormParams();
      let btns = [];

      btns.push({
        key: "search",
        icon: <i className='icon-workflow-Right-menu--search'/>,
        content:getLabel(197,'搜索'),
        onClick: key =>{superviseStore.getSessionkey();}
      });

      btns.push({
          key: "batchHandle",
          icon: <i className='icon-coms-Batch-delete'/>,
          content:getLabel(84561,'批量督办'),
          disabled:  operBtnKey == "batchAttention"||selectedLen<=0,
          onClick: key =>{superviseStore.setShowBatchSubmit(true)}
      });

      btns.push({
        key: "batchAttention",
        icon: <i className='icon-coms-Subscribe'/>,
        content: getLabel(503955,'批量关注'),
        disabled: operBtnKey !== "batchAttention"||selectedLen <= 0,
        onClick: this.batchAttention.bind(this)
    });

      btns.push({
          key:"colSet",
          icon: <i className='icon-coms-Custom'/>,
          content:getLabel(32535,'显示列定制'),
          onClick: key =>{
            tableStore.setColSetVisible(true);
            tableStore.tableColSet(true);
          }
      });
     return btns;
  }



}

export default WeaTools.tryCatch(React,
    props => <WeaErrorPage ecId={`${this && this.props && this.props.ecId || ''}_WeaErrorPage@sbrzcn`} msg={ props.error ? props.error : getLabel(383324,'对不起，该页面异常，请联系管理员！')} />,
    {error: ""}
    )(Supervise);

//操作菜单方法
window.requestSuperviseUtil  =(function(){
  return {
      //督办
      handle(requestid){
        superviseStore.setShowBatchSubmit(true);
        superviseStore.handleParams = {method:'only',requestids:requestid};
      },
      //短信催办
      smsHandle(requestid){
        superviseStore.setSmsParams({requestid});
        superviseStore.setSmsVisible(true);
      },
      //邮件催办
      emailHandle(requestid){
        superviseStore.getSendEmailInfo({requestid});
        // superviseStore.setEmailVisible(true);
      }
  }
})()
